package com.chuanqi.admin.controller; 

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.chuanqi.admin.domain.LoginLog;
import com.chuanqi.admin.service.LoginLogService;
import com.chuanqi.admin.shiro.UserRealm.ShiroUser;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;


@Controller
@RequestMapping("/admin")
public class AdminLoginController {
	@Autowired
	private LoginLogService loginLogService;

    @RequestMapping(value = "/login")
    public String loginPost(HttpServletRequest req, Model model) {
        String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
        String error = null;
        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if(LockedAccountException.class.getName().equals(exceptionClassName)) {
            error = "账户被禁了";
        } else if("jCaptcha.error".equals(exceptionClassName)) {
            error = "验证码错误";
        } else if(exceptionClassName != null) {
            error = "其他错误：" + exceptionClassName;
        }
                
        model.addAttribute("error", error);
        return "authc/login";
    }	
    
    @RequestMapping(value = "/unauthorized")
    public String unauthorizedGet(HttpServletRequest req, Model model) {
        return "unauthorized";
    }
    
    @RequestMapping(value = "/logout", method=RequestMethod.GET)
    public String logoutGet(HttpServletRequest request, Model model) {
    	Subject currentUser = SecurityUtils.getSubject();
    	ShiroUser user = (ShiroUser) currentUser.getPrincipal();
    	
        if(user!=null){
        	Date now = new Date();			
    		SimpleDateFormat simpleDateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");			
    		Timestamp loginTime = Timestamp.valueOf(simpleDateformat.format(now));		 
    	    
    		String ip = getClientIpAddress(((HttpServletRequest)request));	   		
    		String mac = getMACAddress(ip);    		
    		Long userId = user.getId();
    		
            LoginLog loginLog = new LoginLog(userId.intValue(), ip, mac, true, loginTime);
            loginLogService.insert(loginLog);       	
        }
        currentUser.logout();  
        return "authc/logout";
        
    }     
    
    private String getClientIpAddress(HttpServletRequest request) { 
        String ip = request.getHeader("x-forwarded-for"); 
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
            ip = request.getHeader("Proxy-Client-IP"); 
        } 

        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP"); 
        } 

        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
            ip = request.getRemoteAddr(); 
        } 
        
        if(ip!=null && ip.contains(",")){
        	ip = ip.substring(0,ip.indexOf(','));
        }			

        System.out.println("本次登录的用户IP地址："+ ip);
        return ip;
    }
    
    private String getMACAddress(String ip) {
		String str = "";
		String macAddress = "";
		try {
			Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
			InputStreamReader ir = new InputStreamReader(p.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			for (int i = 1; i < 100; i++) {
				str = input.readLine();
				if (str != null) {
					if (str.indexOf("MAC") > 1) {
						macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
						break;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace(System.out);
		}
		return macAddress;
	}

}

